﻿/* 
 * Author:曾洋
 * Descript:随机生成验证码
 * Date:2011-9-21
 */
using System;
using System.Drawing;

namespace ZX.WebApp
{
    public partial class VCode : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                Session["vcode"] = null;
                string vcode = GetVcode(4);
                Session["vcode"] = vcode;
                CreateImg(vcode);
            }
        }

        /// <summary>
        /// 返回验证码值
        /// </summary>
        /// <param name="vCount">位数</param>
        /// <returns>值</returns>
        private string GetVcode(int vCount)
        {
            string strAll = "1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,R,S,T,U,V,W,X,Y,Z";
            string[] strAllArr = strAll.Split(',');
            string vcodeReturn = "";
            int temp = -1;
            Random rom = new Random();
            for (int i = 0; i < vCount; i++)
            {
                if (temp != -1)
                {
                    rom = new Random(i * temp * (int)DateTime.Now.Ticks);
                }
                int t = rom.Next(32);
                if (t == temp)
                {
                    return GetVcode(vCount);
                }
                temp = t;
                vcodeReturn = vcodeReturn + strAllArr[t];
            }
            return vcodeReturn;
        }

        /// <summary>
        /// 画干扰图片
        /// </summary>
        /// <param name="vcodeStr"></param>
        private void CreateImg(string vcodeStr)
        {
            int vwidth = vcodeStr.Length * 12;
            Bitmap bmp = new Bitmap(vwidth, 23);
            Graphics gs = Graphics.FromImage(bmp);
            Font vfont = new Font("Arial", 10, System.Drawing.FontStyle.Bold);
            Brush br = new System.Drawing.SolidBrush(Color.White);
            gs.Clear(Color.YellowGreen);
            gs.DrawString(vcodeStr, vfont, br, 3, 3);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            Response.Clear();
            Response.ContentType = "image/JPEG";
            Response.BinaryWrite(ms.ToArray());
            gs.Dispose();
            bmp.Dispose();
        }
    }
}